<template>
    <view class="bg-white mt-2 pl-[20rpx] pr-[20rpx] pb-[20rpx]">
        <u-form
            labelPosition="left"
            :model="formData"
            :rules="formRules"
            ref="formRef"
        >
            <u-form-item
                label="邮箱"
                prop="email"
                borderBottom
                labelWidth="60"
            >
                <u-input
                    type="text"
                    name="email"
                    border="bottom"
                    placeholder="请输入邮箱"
                    v-model="formData.email"
                ></u-input>
            </u-form-item>
        </u-form>
        <view class="submit-btn">
            <u-button type="primary" text="确定" @click="submit"></u-button>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import useUserStore from "@/stores/user";
import { test } from "@/uni_modules/uview-plus";
import { storeToRefs } from "pinia";
import { messageSuccess } from "@/utils/message";
import { useRoute } from "@/hooks/useRoute";
import { getUserInfo, updateEmail } from "@/api/user";

const formRef = ref(null);

const userStore = useUserStore();
const { isLogin } = storeToRefs(userStore);

const formData = reactive({
    email: "",
});

const formRules = reactive({
    email: [
        {
            required: true,
            message: "请输入邮箱",
            trigger: ["change", "blur"],
        },
        {
            validator: (rule, value, callback) => {
                return test.email(value);
            },
            message: "邮箱不符合要求",
            trigger: ["change", "blur"],
        },
    ],
});

const getUserData = async () => {
    if (isLogin.value) {
        const res = await getUserInfo();
        formData.email = res.email;
    }
};

const jumpClick = (url) => {
    useRoute().jumpTo({ url: url });
};

const submit = () => {
    formRef.value.validate().then(async (valid) => {
        if (valid) {
            await updateEmail({
                email: formData.email,
            });
            messageSuccess("修改成功");
        }
    });
};

getUserData();
</script>

<style lang="scss" scoped>
.submit-btn {
    margin-top: 50rpx;
    padding: 0 20rpx;
}
</style>
